// hooks/taskdata.ts
// 数据管理相关的 Hook

import { useState, useCallback, useEffect } from 'react'
import { useAuth } from '@/hooks/useAuth'
import { DataAPI, DataTransformer } from '@/lib/taskdata'
import type { 
  DataRecord, 
  DataFilters, 
  CreateDataRequest,
  UpdateDataRequest,
  DataListResponse,
  DataType
} from '@/types/taskdata'

/**
 * 数据表单接口
 */
export interface DataForm {
  name: string
  description: string
  type: DataType
  location: string
  collection_date: string
  crop_type?: string
  attachments: File[]
}

/**
 * 数据验证工具类
 */
export class DataValidator {
  /**
   * 验证数据表单
   */
  static validateForm(formData: DataForm): Partial<Record<keyof DataForm, string>> {
    const errors: Partial<Record<keyof DataForm, string>> = {}

    if (!formData.name.trim()) {
      errors.name = '数据名称不能为空'
    }

    if (!formData.description.trim()) {
      errors.description = '数据描述不能为空'
    }

    if (!formData.type) {
      errors.type = '请选择数据类型'
    }

    if (!formData.location.trim()) {
      errors.location = '采集地点不能为空'
    }

    if (!formData.collection_date) {
      errors.collection_date = '采集时间不能为空'
    }

    return errors
  }

  static hasRequiredFields(formData: DataForm): boolean {
    return !!(formData.name.trim() && 
             formData.description.trim() &&
             formData.type &&
             formData.location.trim() &&
             formData.collection_date)
  }
}

/**
 * 数据管理 Hook
 * 提供数据记录的CRUD操作和状态管理
 */
export function useDataRecords() {
  const { user, isAuthenticated } = useAuth()
  const [dataRecords, setDataRecords] = useState<DataRecord[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  // 权限检查（基于用户类型）
  const isLaboratoryUser = user?.user_type === 'laboratory'
  const canCreateData = isAuthenticated
  const canEditData = isAuthenticated
  const canDeleteData = isLaboratoryUser

  /**
   * 加载数据记录列表
   */
  const fetchDataRecords = useCallback(async (filters?: DataFilters) => {
    if (!isAuthenticated) return

    try {
      setLoading(true)
      setError(null)
      
      const response: DataListResponse = await DataAPI.getDataRecords(filters)
      
      // 如果是普通用户，只显示自己负责的数据
      let filteredRecords = Array.isArray(response.records) ? response.records : []
      if (!isLaboratoryUser && user?.full_name) {
        filteredRecords = filteredRecords.filter(record => 
          record.owner === user.full_name
        )
      }
      
      setDataRecords(filteredRecords)
    } catch (err: any) {
      console.error('获取数据记录失败:', err)
      setError(err.message || '获取数据记录失败')
      setDataRecords([])
    } finally {
      setLoading(false)
    }
  }, [isAuthenticated, isLaboratoryUser, user?.full_name])

  /**
   * 创建新数据记录
   */
  const createDataRecord = useCallback(async (
    projectId: string,
    dataForm: DataForm
  ): Promise<{
    success: boolean
    message?: string
    data?: DataRecord
  }> => {
    if (!canCreateData) {
      return { success: false, message: '您没有权限创建数据记录' }
    }

    try {
      setLoading(true)
      setError(null)

      // 验证必填字段
      if (!DataValidator.hasRequiredFields(dataForm)) {
        return { success: false, message: '请填写所有必填字段' }
      }

      // 转换表单数据为 API 请求格式
      const transformedData = DataTransformer.formToRequest(dataForm)
      const requestData: CreateDataRequest = {
        ...transformedData,
        project_id: projectId
      } as CreateDataRequest

      const response = await DataAPI.createDataRecord(requestData)
      
      // 刷新数据列表
      await fetchDataRecords()
      
      return { 
        success: true, 
        message: '数据记录创建成功',
        data: response.data
      }
    } catch (err: any) {
      console.error('创建数据记录失败:', err)
      const message = err.message || '创建数据记录失败'
      setError(message)
      return { success: false, message }
    } finally {
      setLoading(false)
    }
  }, [canCreateData, fetchDataRecords])

  /**
   * 更新数据记录
   */
  const updateDataRecord = useCallback(async (
    dataId: string, 
    dataForm: DataForm
  ): Promise<{
    success: boolean
    message?: string
    data?: DataRecord
  }> => {
    if (!canEditData) {
      return { success: false, message: '您没有权限编辑数据记录' }
    }

    try {
      setLoading(true)
      setError(null)

      // 验证必填字段
      if (!DataValidator.hasRequiredFields(dataForm)) {
        return { success: false, message: '请填写所有必填字段' }
      }

      // 转换表单数据为 API 请求格式
      const requestData = DataTransformer.formToRequest(dataForm) as UpdateDataRequest

      const response = await DataAPI.updateDataRecord(dataId, requestData)
      
      // 更新本地数据列表
      setDataRecords(prev => Array.isArray(prev) ? prev.map(record => 
        record.id === dataId ? response.data : record
      ) : [])
      
      return { 
        success: true, 
        message: '数据记录更新成功',
        data: response.data
      }
    } catch (err: any) {
      console.error('更新数据记录失败:', err)
      const message = err.message || '更新数据记录失败'
      setError(message)
      return { success: false, message }
    } finally {
      setLoading(false)
    }
  }, [canEditData])

  /**
   * 删除数据记录
   */
  const deleteDataRecord = useCallback(async (dataId: string): Promise<{
    success: boolean
    message?: string
  }> => {
    if (!canDeleteData) {
      return { success: false, message: '您没有权限删除数据记录' }
    }

    try {
      setLoading(true)
      setError(null)

      await DataAPI.deleteDataRecord(dataId)
      
      // 从本地列表中移除
      setDataRecords(prev => Array.isArray(prev) ? prev.filter(record => record.id !== dataId) : [])
      
      return { success: true, message: '数据记录删除成功' }
    } catch (err: any) {
      console.error('删除数据记录失败:', err)
      const message = err.message || '删除数据记录失败'
      setError(message)
      return { success: false, message }
    } finally {
      setLoading(false)
    }
  }, [canDeleteData])

  /**
   * 上传数据文件
   */
  const uploadDataFiles = useCallback(async (
    dataId: string, 
    files: File[]
  ): Promise<{
    success: boolean
    message?: string
  }> => {
    if (!canEditData) {
      return { success: false, message: '您没有权限上传文件' }
    }

    try {
      setLoading(true)
      setError(null)

      await DataAPI.uploadDataFiles(dataId, files)
      
      // 刷新数据列表以获取最新的文件信息
      await fetchDataRecords()
      
      return { success: true, message: '文件上传成功' }
    } catch (err: any) {
      console.error('上传文件失败:', err)
      const message = err.message || '上传文件失败'
      setError(message)
      return { success: false, message }
    } finally {
      setLoading(false)
    }
  }, [canEditData, fetchDataRecords])

  /**
   * 删除数据文件
   */
  const deleteDataFile = useCallback(async (
    dataId: string, 
    fileId: string
  ): Promise<{
    success: boolean
    message?: string
  }> => {
    if (!canEditData) {
      return { success: false, message: '您没有权限删除文件' }
    }

    try {
      setLoading(true)
      setError(null)

      await DataAPI.deleteDataFile(dataId, fileId)
      
      // 刷新数据列表以获取最新的文件信息
      await fetchDataRecords()
      
      return { success: true, message: '文件删除成功' }
    } catch (err: any) {
      console.error('删除文件失败:', err)
      const message = err.message || '删除文件失败'
      setError(message)
      return { success: false, message }
    } finally {
      setLoading(false)
    }
  }, [canEditData, fetchDataRecords])

  /**
   * 下载数据文件
   */
  const downloadDataFile = useCallback(async (
    dataId: string, 
    fileId: string,
    fileName: string
  ) => {
    try {
      await DataAPI.downloadDataFile(dataId, fileId, fileName)
    } catch (err: any) {
      console.error('下载文件失败:', err)
      setError(err.message || '下载文件失败')
    }
  }, [])

  /**
   * 批量删除数据记录
   */
  const batchDeleteDataRecords = useCallback(async (dataIds: string[]): Promise<{
    success: boolean
    message?: string
  }> => {
    if (!canDeleteData) {
      return { success: false, message: '您没有权限批量删除数据记录' }
    }

    try {
      setLoading(true)
      setError(null)

      await DataAPI.batchDeleteDataRecords(dataIds)
      
      // 从本地列表中移除
      setDataRecords(prev => Array.isArray(prev) ? 
        prev.filter(record => !dataIds.includes(record.id)) : [])
      
      return { success: true, message: `成功删除 ${dataIds.length} 条数据记录` }
    } catch (err: any) {
      console.error('批量删除失败:', err)
      const message = err.message || '批量删除失败'
      setError(message)
      return { success: false, message }
    } finally {
      setLoading(false)
    }
  }, [canDeleteData])

  // 初始化加载数据
  useEffect(() => {
    if (isAuthenticated) {
      fetchDataRecords()
    }
  }, [isAuthenticated, fetchDataRecords])

  return {
    // 数据
    dataRecords,
    loading,
    error,
    
    // 权限
    canCreateData,
    canEditData,
    canDeleteData,
    isLaboratoryUser,
    
    // 方法
    fetchDataRecords,
    createDataRecord,
    updateDataRecord,
    deleteDataRecord,
    uploadDataFiles,
    deleteDataFile,
    downloadDataFile,
    batchDeleteDataRecords,
    
    // 清除错误
    clearError: () => setError(null)
  }
}

/**
 * 数据表单管理 Hook
 */
export function useDataForm(initialData?: DataRecord) {
  const [formData, setFormData] = useState<DataForm>({
    name: initialData?.name || '',
    description: initialData?.description || '',
    type: initialData?.type || 'others',
    location: initialData?.location || '',
    collection_date: initialData?.collection_date || '',
    crop_type: initialData?.crop_type || '',
    attachments: []
  })

  const [errors, setErrors] = useState<Partial<Record<keyof DataForm, string>>>({})

  /**
   * 更新表单字段
   */
  const updateField = useCallback((field: keyof DataForm, value: any) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }))
    
    // 清除该字段的错误
    if (errors[field]) {
      setErrors(prev => ({
        ...prev,
        [field]: undefined
      }))
    }
  }, [errors])

  /**
   * 添加附件
   */
  const addAttachments = useCallback((files: File[]) => {
    setFormData(prev => ({
      ...prev,
      attachments: [...prev.attachments, ...files]
    }))
  }, [])

  /**
   * 移除附件
   */
  const removeAttachment = useCallback((index: number) => {
    setFormData(prev => ({
      ...prev,
      attachments: prev.attachments.filter((_, i) => i !== index)
    }))
  }, [])

  /**
   * 验证表单
   */
  const validateForm = useCallback((): boolean => {
    const newErrors = DataValidator.validateForm(formData)
    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }, [formData])

  /**
   * 重置表单
   */
  const resetForm = useCallback(() => {
    setFormData({
      name: '',
      description: '',
      type: 'others',
      location: '',
      collection_date: '',
      crop_type: '',
      attachments: []
    })
    setErrors({})
  }, [])

  return {
    formData,
    errors,
    updateField,
    addAttachments,
    removeAttachment,
    validateForm,
    resetForm,
    setFormData
  }
}